package com.hhxy.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hhxy.pojo.User;

/**
 * 练习Java对象和JSON的转换
 */
public class FastJsonDemo {
    public static void main(String[] args) {
        //创建一个Java对象
        User user = new User("张三", 18, '男');

        //1、将Java对象转成JSON字符串
        String json = JSON.toJSONString(user);
        System.out.println(json);//{"age":18,"gender":"男","name":"张三"}

        //2、将JSON字符串转成Java对象
        JSONObject u1 = JSON.parseObject("{\"age\":18,\"gender\":\"男\",\"name\":\"张三\"}");
        System.out.println(u1);//不设置默认是转成JSON对象，{"gender":"男","name":"张三","age":18}
        User u2 = JSON.parseObject("{\"age\":18,\"gender\":\"男\",\"name\":\"张三\"}",User.class);
        System.out.println(u2);//User{name='张三', age=18, gender=男}(记得重写Object的toString方法)
    }
}
